# coding: utf-8

"""
    @Author :   zsj
    @File   :   base_service.py
    @Time   :   2024-08-12
    @Desc   :   基础服务类，封装通用CRUD操作
"""

from src.core.session import SQLCON
from src.common.response import success_response, fail_response
from src.utils.tools import get_cur_time
from src.core.logconfig import log
from typing import Type, Optional, Any, Generic, TypeVar
from sqlmodel import SQLModel, select

T = TypeVar('T', bound=SQLModel)
CreateSchema = TypeVar('CreateSchema', bound=SQLModel)
UpdateSchema = TypeVar('UpdateSchema', bound=SQLModel)


class BaseService(Generic[T, CreateSchema, UpdateSchema]):
    """基础服务类，提供通用的CRUD操作"""
    
    def __init__(self, entity: Type[T]):
        """
        初始化服务类
        
        Args:
            entity: 数据库实体类
        """
        self.entity = entity
        self.db = SQLCON
        self.log = log.logger
    
    async def get_list(self) -> Any:
        """获取所有数据列表"""
        try:
            result = self.db.db_query(self.entity)
            return success_response(result)
        except Exception as e:
            self.log.error(f"获取{self.entity.__tablename__}列表失败: {str(e)}")
            return fail_response(f"获取数据失败: {str(e)}")
    
    async def get_by_id(self, data_id: int) -> Any:
        """根据ID获取单条数据"""
        try:
            result = self.db.db_query_by_id(self.entity, data_id)
            if not result:
                return fail_response("数据不存在")
            return success_response(result)
        except Exception as e:
            self.log.error(f"获取{self.entity.__tablename__}数据失败: {str(e)}")
            return fail_response(f"获取数据失败: {str(e)}")
    
    async def create(self, create_data: CreateSchema, **kwargs) -> Any:
        """
        创建新数据
        
        Args:
            create_data: 创建数据模型
            **kwargs: 额外的自定义字段
        """
        try:
            # 如果create_data有create_time字段，自动设置当前时间
            if hasattr(create_data, 'create_time'):
                setattr(create_data, 'create_time', get_cur_time())
            
            # 设置额外的自定义字段
            for key, value in kwargs.items():
                if hasattr(create_data, key):
                    setattr(create_data, key, value)
            
            result = self.db.db_create(create=create_data, entity=self.entity)
            return success_response(result)
        except Exception as e:
            self.log.error(f"创建{self.entity.__tablename__}数据失败: {str(e)}")
            return fail_response(f"创建数据失败: {str(e)}")
    
    async def update(self, update_data: UpdateSchema) -> Any:
        """
        更新数据
        
        Args:
            update_data: 更新数据模型
        """
        try:
            # 如果update_data有update_time字段，自动设置当前时间
            if hasattr(update_data, 'update_time'):
                setattr(update_data, 'update_time', get_cur_time())
            
            result = self.db.db_update(entity=self.entity, update=update_data)
            if isinstance(result, dict) and 'msg' in result:
                return fail_response(result['msg'])
            return success_response(result)
        except Exception as e:
            self.log.error(f"更新{self.entity.__tablename__}数据失败: {str(e)}")
            return fail_response(f"更新数据失败: {str(e)}")
    
    async def delete(self, id: int) -> Any:
        """删除数据"""
        try:
            result = self.db.db_del_by_id(self.entity, id)
            if not result:
                return fail_response("删除失败，数据不存在")
            return success_response("删除成功")
        except Exception as e:
            self.log.error(f"删除{self.entity.__tablename__}数据失败: {str(e)}")
            return fail_response(f"删除数据失败: {str(e)}")
    
    async def query_with_filter(self, sql, single: bool = False) -> Any:
        """带条件查询"""
        try:
            result = self.db.db_query_filter(self.entity, sql, single)
            return success_response(result)
        except Exception as e:
            self.log.error(f"条件查询{self.entity.__tablename__}失败: {str(e)}")
            return fail_response(f"查询失败: {str(e)}")